package com.shang.spring.aop.hello;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class AtithCalculatorLoggingProxy {

    //要代理的对象
    private AtithCalculator target;

    public AtithCalculatorLoggingProxy(AtithCalculator target) {
        this.target = target;
    }

    public AtithCalculator getLoggingProxy(){
        AtithCalculator proxy = null;

        //代理对象由哪一个类加载器负责加载
        ClassLoader loader = target.getClass().getClassLoader();
        //代理对象的类型，即其中有哪些方法
        Class[] innterfaces = {AtithCalculator.class};

        //当调用代理对象其中的方法时，该执行的代码
        InvocationHandler h = new InvocationHandler() {

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
                System.out.println(methodName + "   " + Arrays.asList(args));
                Object result = method.invoke(target, args);
                System.out.println(methodName + "   " + result);
                return result;
            }
        };
        proxy = (AtithCalculator) Proxy.newProxyInstance(loader,innterfaces,h);

        return proxy;
    }

}
